package com.yangye.pisystem.service.impl;

import com.yangye.picommon.core.service.impl.BaseServiceImpl;
import com.yangye.pisystem.dao.SysUserMapper;
import com.yangye.pisystem.domain.SysUser;
import com.yangye.pisystem.domain.SysUserRole;
import com.yangye.pisystem.dto.SysUserDTO;
import com.yangye.pisystem.service.SysUserRoleService;
import com.yangye.pisystem.service.SysUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by yangye on 2019/7/9
 */
@Service
public class SysUserServiceImpl extends BaseServiceImpl<SysUserMapper, SysUser> implements SysUserService {
	@Autowired
	private SysUserRoleService sysUserRoleService;
	@Value("${pi.sys.user.defaultPassword}")
	private String defaultPassword;

	@Override
	@Transactional
	public SysUser addUser(SysUserDTO sysUserDTO) {
		// 密码加密
		BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
		String encodePwd = bCryptPasswordEncoder.encode(defaultPassword);
		sysUserDTO.setPassword(encodePwd);
		super.add(sysUserDTO);

		// 保存角色
		sysUserRoleService.updateRoles(sysUserDTO.getId(), sysUserDTO.getRoles());
		return sysUserDTO;
	}

	@Override
	public SysUser updateUser(SysUserDTO sysUserDTO) {
		// 不更新密码
		sysUserDTO.setPassword(null);
		super.update(sysUserDTO);

		// 保存角色
		sysUserRoleService.updateRoles(sysUserDTO.getId(), sysUserDTO.getRoles());
		return sysUserDTO;
	}

	@Override
	public SysUser changePassword(SysUserDTO sysUserDTO) {
		// TODO 修改密码
		return null;
	}

	@Override
	public SysUser findByUsername(String username) {
		SysUser query = new SysUser();
		query.setUsername(username);
		return dao.selectOne(query);
	}

	@Override
	public SysUser get(Long id) {
		SysUser sysUser = super.get(id);
		List<SysUserRole> userRoles = sysUserRoleService.getByUserId(id);
		List<Long> roleIds = new ArrayList<>();
		for (SysUserRole userRole : userRoles) {
			roleIds.add(userRole.getRoleId());
		}
		SysUserDTO sysUserDTO = new SysUserDTO();
		BeanUtils.copyProperties(sysUser, sysUserDTO);
		sysUserDTO.setRoles(roleIds);
		return sysUserDTO;
	}
}
